<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
 .header {
	 display: flex;
	 align-items: center;
	 justify-content: space-between;
	 padding: 10px 20px;
	 /* 			background-color:gainsboro; */
 }

 .logo {
	 height: 50px;
 }

 .title {
	 font-size: 24px;
	 font-weight: bold;
 }

 .links {
	 display: flex;
	 align-items: center;
 }

 .links el-link {
	 margin-left: 10px;
 }

 .user-info {
	 display: flex;
	 align-items: center;
 }

 .avatar {
	 margin-right: 10px;
 }

 .username a {
	 color: #333;
	 text-decoration: none;
 }
 /* 绿色点样式 */
 .green-point {
	 width: 10px;
	 height: 10px;
	 background-color: green;
	 border-radius: 50%;
	 margin-right: 10px;
	 display: inline-block;
 }

 /* 红色点样式 */
 .red-point {
	 width: 10px;
	 height: 10px;
	 background-color: red;
	 border-radius: 50%;
	 margin-right: 10px;
	 display: inline-block;
 }
 /* 橘黄色点样式 */
 .orange-point {
	 width: 10px;
	 height: 10px;
	 background-color: orange;
	 border-radius: 50%;
	 margin-right: 10px;
	 display: inline-block;
 }
 	.avatar-container {
 	  position: relative;
 	  display: inline-block;
 	}
 
 	.avatar-uploader {
 	  display: inline-block;
 	  cursor: pointer;
 	  position: relative;
 	  overflow: hidden;
 	  border: 1px solid #eee;
 	  border-radius: 50%;
 	  width: 80px;
 	  height: 80px;
 	}
 
 	.avatar {
 	  width: 100%;
 	  height: 100%;
 	  object-fit: cover;
 	}
 
 	.avatar-uploader-icon {
 	  font-size: 24px;
 	  color: #8c939d;
 	  position: absolute;
 	  top: 50%;
 	  left: 50%;
 	  transform: translate(-50%, -50%);
 	}
    </style>
    <script src="../js/vue.js"></script>
    <script src="../element-ui/lib/index.js"></script>
    <link rel="stylesheet" href="../element-ui/lib/theme-chalk/index.css">
    <script src="../js/axios-0.18.0.js"></script>
    <!-- 引入百度地图 API -->
    <script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=rXA8iQy9OhoIKkZEjWbO0xJR5c40gDcg"></script>
    <script src="https://api.map.baidu.com/api?v=1.0&amp;type=webgl&amp;ak=rXA8iQy9OhoIKkZEjWbO0xJR5c40gDcg"></script>
    <title>群星网约车</title>
	<link rel="icon" href="../image/carMR.png" type="image/png">
</head>
<body>
	<div id="app">
		<div class="header">
			<img class="logo" src="../image/carMR.png">
			<span class="title">群星网约车祝您一帆风顺</span>
			<div class="links">
				<el-link href="driverMain.html" target="_self" :underline="false">主页&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
				<el-link href="orderDriverInfo.html" target="_self" :underline="false">我的订单&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
				<el-link href="taxiInfo.html" target="_blank" :underline="false">群星简介&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
				<el-link href="driverInfo.html" target="_self" :underline="false">个人中心&nbsp;&nbsp;&nbsp;&nbsp;</el-link>
				&nbsp;&nbsp;&nbsp;&nbsp;
				<div v-if="driverStatus === '在线'">
					<div class="green-point"></div>
				</div>
				<div v-else-if="driverStatus === '离线'">
					<div class="red-point"></div>
				</div>
				<div v-else>
					<div class="orange-point"></div>
				</div>
				<el-select v-model="driverStatus" placeholder="选择司机状态" style="width: 120px;">
					<el-option label="离线" value="离线"></el-option>
					<el-option label="在线" value="在线"></el-option>
					<el-option label="接单中" value="接单中"></el-option>
				</el-select>
			</div>
			<div class="user-info">
				<div>
					<el-avatar :src="avatar"></el-avatar>
				</div>
				&nbsp;&nbsp;&nbsp;&nbsp;
				<span v-if="!isEditing" class="username">
			<a id="uname" href="javascript:void(0)" @click="isEditing = true">{{ displayUsername }}</a>
		  </span>
				<input v-else v-model="displayUsername" @blur="isEditing = false" @keyup.enter="isEditing = false" />
				&nbsp;&nbsp;&nbsp;&nbsp;
				<el-link target="_blank" :underline="false" @click="exitInfo">退出系统</el-link>
				&nbsp;&nbsp;&nbsp;&nbsp;
			</div>
		</div>
		<el-container>
		<el-header>个人中心</el-header>
		<el-main>
		  <el-row :gutter="20">
			<el-col :span="12">
			  <el-card>
				<div slot="header" class="clearfix">
				  <span>个人信息</span>
				</div>
				<el-avatar :size="80" :src="avatar"></el-avatar>
				<p>用户名：{{userName}}</p>
				<p>邮箱：{{email}}</p>
				<p>电话：{{originalPhone}}</p>
				<p>车牌号：{{licensePlate}}</p>
			  </el-card>
			</el-col>
			<el-col :span="12">
			  <el-card>
				<div slot="header" class="clearfix">
				  <span>账户设置</span>
				</div>
				<el-row :gutter="20">
				  <el-col :span="12">
					<div class="avatar-container">
					  <el-upload
						class="avatar-uploader"
						action="/driver/drivers/common/upload"
						:show-file-list="false"
						:before-upload="beforeAvatarUpload"
						:on-success="handleAvatarSuccess">
						<i class="el-icon-plus avatar-uploader-icon"></i>
					  </el-upload>
					</div>
				  </el-col>
				</el-row>
				<p @click="dialogVisible = 'password'" style="cursor: pointer;">修改密码</p>
				<p @click="dialogVisible = 'email'" style="cursor: pointer;">修改邮箱</p>
				<p @click="dialogVisible = 'phone'" style="cursor: pointer;">修改电话</p>
				<p @click="dialogVisible = 'name'" style="cursor: pointer;">修改昵称</p>
				<el-dialog title="修改密码" :visible.sync="dialogVisible" v-if="dialogVisible === 'password'">
				  <el-input placeholder="请输入原密码" v-model="originalPassword"></el-input>
				  <br />
				  <br />
				  <el-input placeholder="请输入新密码" v-model="password"></el-input>
				  <span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = ''">取消</el-button>
					<el-button type="primary" @click="submitChange('password')">确定</el-button>
				  </span>
				</el-dialog>
				<el-dialog title="修改邮箱" :visible.sync="dialogVisible" v-if="dialogVisible === 'email'">
				  <el-input placeholder="请输入新邮箱" v-model="newEmail"></el-input>
				  <br />
				  <br />
				  <el-input placeholder="请输入验证码" v-model="verificationCode"></el-input>
				  <br />
				  <br />
				  <el-button @click="sendVerificationCode">获取验证码</el-button>
				  <span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = ''">取消</el-button>
					<el-button type="primary" @click="submitEmailChange">确定</el-button>
				  </span>
				</el-dialog>
				<el-dialog title="修改电话" :visible.sync="dialogVisible" v-if="dialogVisible === 'phone'">
				  <el-input placeholder="请输入新电话" v-model="phone"></el-input>
				  <span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = ''">取消</el-button>
					<el-button type="primary" @click="submitChange('phone')">确定</el-button>
				  </span>
				</el-dialog>
				  <el-dialog title="修改昵称" :visible.sync="dialogVisible" v-if="dialogVisible === 'name'">
					  <el-input placeholder="请输入新昵称" v-model="name"></el-input>
					  <span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = ''">取消</el-button>
					<el-button type="primary" @click="submitChange('name')">确定</el-button>
				  </span>
				  </el-dialog>
			  </el-card>
			</el-col>
		  </el-row>
		  <el-row :gutter="20" style="margin-top: 20px;">
			<el-col :span="12">
				<el-card>
				  <div slot="header" class="clearfix">
					<span>订单管理</span>
				  </div>
				  <el-table :data="orders" style="width: 100%;max-height: 210px;overflow-y: auto;">
					<el-table-column prop="orderNumber" label="订单号" width="180"></el-table-column>
					<el-table-column prop="userName" label="用户名称" width="100"></el-table-column>
					<el-table-column prop="phoneNumber" label="手机号" width="180"></el-table-column>
					<el-table-column prop="status" label="订单状态" width="120"></el-table-column>
				  </el-table>
				</el-card>
			</el-col>
			<el-col :span="12">
			  <el-card>
				<div slot="header" class="clearfix">
				  <span>行程记录</span>
				</div>
				<el-table :data="trips" style="width: 100%;max-height: 210px;overflow-y: auto;">
				  <el-table-column prop="date" label="日期" width="180"></el-table-column>
				  <el-table-column prop="time" label="时间" width="100"></el-table-column>
				  <el-table-column prop="start" label="出发地" width="150"></el-table-column>
				  <el-table-column prop="end" label="目的地" width="150"></el-table-column>
				  <el-table-column prop="cost" label="收入" width="100"></el-table-column>
				</el-table>
			  </el-card>
			</el-col>
		  </el-row>
		</el-main>
	  </el-container>
	</div>
    <script>
		// request拦截器，将用户token放入头中
		axios.interceptors.request.use(
				config => {
					let token = localStorage.getItem("token"); // 确保 token 正确存储在 localStorage 中
					if (token) {
						config.headers['token'] = token;
					}
					return config;
				},
				error => {
					console.log(error);
					return Promise.reject(error);
				}
		);
        new Vue({
            el: '#app',
            data: {
				userId: '',
				orderId: '',
				userName: '',
				name: "",
				avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', // 默认头像链接				
				websocket: null,
				driverStatus: '离线',
				dialogVisible: '', // 控制哪个对话框显示
				password: '',
				originalPassword: '',
				email: '',
				newEmail: '',
				verificationCode: '',
				sentCode: '',
				phone: '',
				originalPhone: '',
				licensePlate: '',
				isEditing: false,
				trips: [
					{ date: '2024-06-15', time: '08:00', start: '北京西站', end: '北京南站', cost: '30元' },
					{ date: '2024-06-14', time: '14:00', start: '国贸', end: '天安门', cost: '20元' },
					{ date: '2024-06-13', time: '09:30', start: '首都国际机场', end: '王府井', cost: '50元' }
						],
				orders: [
				  { orderNumber: '20240617001', userName: '张师傅', phoneNumber: '13873945267', status: '已发货' },
				  { orderNumber: '20240616002', userName: '王师傅', phoneNumber: '13873945267', status: '待发货' },
				  { orderNumber: '20240615003', userName: '李师傅', phoneNumber: '13873945267', status: '已完成' },
				  // 插入更多订单数据
				],
            },
			created() {
				this.driverStatus = localStorage.getItem("driverStatus");
			},
            mounted() {
				var id=localStorage.getItem('userId');
				this.userId = parseInt(id, 10);
				this.userName = localStorage.getItem('userName');
				this.orderId=localStorage.getItem('orderId');
/*				this.updateDriverStatus('3');*/
				this.email=localStorage.getItem('email');
				this.originalPhone=localStorage.getItem('phoneNumber');
				this.avatar = localStorage.getItem('pic');
				this.licensePlate=localStorage.getItem('licensePlate');
				axios.get('/order/orders/getByDriverId?driverId='+this.userId)
				.then(response=>{
					if(response.data.code==1){
						this.orders = response.data.data.map(order => {
							// 将status转换为相应的文本描述
							switch (order.status) {
								case '1':
									order.status = '待处理';
									break;
								case '2':
									order.status = '已确认';
									break;
								case '3':
									order.status = '已完成';
									break;
								case '4':
									order.status = '已取消';
									break;
								default:
									order.status = '待付款'; // 添加默认情况处理
							}
							return order;
						});
					}
				});
				axios.get('/order/orders/getByDriverId2?driverId='+this.userId)
				.then(response=>{
					if(response.data.code==1){
						this.trips = response.data.data.map(order => {
							const [date, time] = order.orderDate.split('T');
							const cost = (order.totalAmount==null) ? '未接单' : order.totalAmount + '元';
							return {
								date: date,
								time: time,
								start: order.departureLocation,
								end: order.destinationLocation,
								cost: cost
							};
						});
					}
				});
				/*
				if (this.userName === null) {
					this.$message.error('非法进入,请先登录');
					setTimeout(() => {
						window.location.href = "../html/login.html";
					}, 3000); // 延迟2秒（2000毫秒）执行
				} */
            },
            methods: {
			sendVerificationCode() {
						this.sentCode = Math.floor(100000 + Math.random() * 900000).toString();
						console.log(`发送验证码 ${this.sentCode} 到邮箱 ${this.email}`);
						this.$message.success('验证码已发送到您的邮箱');
						axios.post('/driver/drivers/sendVerificationCode', {
							driverId: this.userId,
							email: this.email,
							code: this.sentCode
						}).then(response => {
							if (response.data.data.code === 1) {
								this.$message.success('验证码发送成功');
							} else {
								this.$message.error('验证码发送失败');
							}
						});
					},
					submitEmailChange() {
						if (this.verificationCode !== this.sentCode) {
							this.$message.error('验证码错误');
							return;
						}
						axios.post('/driver/drivers/changeEmail', {
							driverId: this.userId,
							newEmail: this.newEmail
						}).then(response => {
							if (response.data.data.code === 1) {
								localStorage.setItem('email',this.newEmail);
								this.email=localStorage.getItem('email');
								this.$message.success('邮箱修改成功');
							} else {
								this.$message.error('邮箱修改失败');
							}
							this.newEmail='';
							this.verificationCode='';
						});
						this.dialogVisible = '';
					},
				exitInfo(){
					axios.put("/driver/drivers/exitStatus?driverId="+this.userId)
							.then(response=>{
								if(response.data.code==1){
									console.log("退出修改状态成功");
								}
							});
					localStorage.removeItem('userId');
					localStorage.removeItem('userName');
					window.location.href = "../html/login.html"; // 页面跳转
				},
				// 发送请求给后端更新司机状态
				updateDriverStatus(status) {
					localStorage.setItem('driverStatus',this.driverStatus);
					axios.put('/driver/drivers/updateDriverStatus', {
						id: this.userId,
						status: status
					})
							.then(response => {
								console.log('更新司机状态成功:', response.data);
							})
							.catch(error => {
								console.error('更新司机状态失败:', error);
							});
				},
				// 监听司机状态变化
				onDriverStatusChange() {
					console.log('司机状态变为：', this.driverStatus);
					// 根据不同的司机状态发送请求给后端
					switch (this.driverStatus) {
						case '离线':
							// 发送请求告诉后端司机已经离线
							this.updateDriverStatus('3');
							break;
						case '在线':
							// 发送请求告诉后端司机已经上线
							this.updateDriverStatus('1');
							break;
						case '接单中':
							// 发送请求告诉后端司机正在接单
							this.updateDriverStatus('2');
							break;
						default:
							console.error('未知司机状态:', this.driverStatus);
							break;
					}
				},
				beforeAvatarUpload(file) {
						  // 自定义的一些上传前的校验逻辑，例如文件类型和大小
						  const isJPG = file.type === 'image/jpeg';
						  const isPNG = file.type === 'image/png';
						  const isLt2M = file.size / 1024 / 1024 < 2;
				
						  if (!isJPG && !isPNG) {
							this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
							return false;
						  }
						  if (!isLt2M) {
							this.$message.error('上传头像图片大小不能超过 2MB!');
							return false;
						  }
						  return true;
						},
						handleAvatarSuccess(response, file) {
						  if (response.code === 1) {
				/*			  this.avatar = URL.createObjectURL(file.raw);*/
							  this.avatar = response.data;
							  const data={
							  	id: this.userId,
							    pic: this.avatar
							  };
							  axios.put('/driver/drivers/updateDriverStatus',data)
							  .then(response=>{
								  if (response.data.code === 1) {
								    localStorage.setItem('pic',this.avatar);
								  	console.log("成功101");
								  }
							  });
				/*			  console.log(this.avatar);*/
							this.$message.success('图片上传成功');
						  } else {
							this.errorMessage = response.data.msg;
							this.$message.error(this.errorMessage);
						  }
						},
						submitChange(type) {
							switch (type) {
								case 'password':
									axios.post('/driver/drivers/changePassword', {
										driverId: this.userId,
										originalPassword: this.originalPassword,
										newPassword: this.password
									}).then(response => {
										if (response.data.data.code === 1) {
											this.$message.success('密码修改成功');
										} else {
											this.$message.error('原密码错误');
										}
										this.originalPassword='';
										this.password='';
									});
									break;
								case 'phone':
									axios.post('/driver/drivers/changePhone', {
										driverId: this.userId,
										phone: this.phone
									}).then(response => {
										if (response.data.data.code === 1) {
											this.$message.success('电话修改成功');
											localStorage.setItem('phoneNumber',this.phone);
											this.originalPhone=localStorage.getItem('phoneNumber');
										} else {
											this.$message.error('电话修改失败');
										}
										this.phone='';
									});
									break;
								case 'name':
									if(this.name==this.userName){
										this.$message.error('不能与原用户名同名哦');
										return;
									}
									axios.post('/driver/drivers/changeName', {
										driverId: this.userId,
										userName: this.name
									}).then(response => {
										if (response.data.data.code === 1) {
											this.$message.success('昵称修改成功');
											localStorage.setItem('userName', this.name);
											this.userName = localStorage.getItem('userName');
										} else {
											this.$message.error('昵称修改失败');
										}
										this.name='';
									});
									break;
							}
							this.dialogVisible = '';
						},
            },
			computed: {
				displayUsername: {
					get() {
						return this.userName ? this.userName : "未登录";
					},
					set(value) {
						this.userName = value;
					}
				}
			},
			watch: {
				// 监听司机状态变化
				driverStatus: 'onDriverStatusChange'
			},

        });
    </script>
	<script>
	</script>
</body>
</html>
